<?php
/**
 * Created by PhpStorm.
 * User: Mysic
 * Date: 2020/10/29
 * Time: 18:16
 */

namespace app\mocks\controller;


use app\api\model\User as UserModel;
use app\api\model\Wxapp as WxappModel;
use app\common\exception\BaseException;
use think\Env;
use think\Request;

class Controller  extends \think\Controller
{
    /* @ver $wxApp 小程序配置 */
    protected $wxApp;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public function _initialize()
    {
        if (!$wxAppId = $this->request->param('wxapp_id')) {
            throw new BaseException(['msg' => '缺少必要的参数：wxapp_id']);
        }
        $this->wxApp = WxappModel::detail($wxAppId);
        if (empty($this->wxApp)) {
            throw new BaseException(['msg' => '当前小程序信息不存在']);
        }
        if ($this->wxApp['is_recycle'] || $this->wxApp['is_delete']) {
            throw new BaseException(['msg' => '当前小程序已删除']);
        }
        if (!$this->wxApp['active']) {
            throw new BaseException(['msg' => '小程序暂未激活']);
        }
    }

    protected function getUser($is_force = true)
    {
        if (!$token = $this->request->param('token')) {
            $is_force && $this->throwError('缺少必要的参数：token', -1);
            return false;
        }

        if (!$user = UserModel::getUser($token)) {
            $is_force && $this->throwError('没有找到用户信息', -1);
            return false;
        }

        return $user;
    }

    /**
     * 输出错误信息
     * @param int $code
     * @param $msg
     * @throws BaseException
     */
    protected function throwError($msg, $code = 0)
    {
        throw new BaseException(['code' => $code, 'msg' => $msg]);
    }
}